﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WeLinkApi.Common
{
    public class Class2Map
    { 
        /// <summary>  
        ///   
        /// 将对象属性转换为key-value对  
        /// </summary>  
        /// <param name="o"></param>  
        /// <returns></returns>  
        public static Dictionary<string, string> ToMap(Object o)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();

            Type t = o.GetType();
            

            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo p in pi)
            {
                if (p.PropertyType.IsArray)
                {
                    map.Add(p.Name, JsonConvert.SerializeObject(p.GetValue(o)));
                }
                else
                {
                    MethodInfo mi = p.GetGetMethod();

                    if (mi != null && mi.IsPublic)
                    {
                        var value = Convert.ToString(mi.Invoke(o, new Object[] {}));
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            map.Add(p.Name, value);
                        }
                    }
                }
                
               
            }

            return map;

        }
        public static SortedDictionary<string, string> ToMapWithString(Object o)
        {
            SortedDictionary<String, string> map = new SortedDictionary<string, string>();

            Type t = o.GetType();

            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo p in pi)
            {
                MethodInfo mi = p.GetGetMethod();

                if (mi != null && mi.IsPublic)
                {
                    map.Add(p.Name, Convert.ToString(mi.Invoke(o, new Object[] { })));
                }
            }

            return map;

        }
    }
}
